package com.wl.nio;

import org.junit.Test;

import java.nio.ByteBuffer;

public class TestBuffer {
    @Test
    public void test1(){
        String str = "abcd";

        //分配一个指定大小的缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        System.out.println("----allocate----");
        System.out.println(buffer.position());
        System.out.println(buffer.limit());
        System.out.println(buffer.capacity());

        //存入数据到缓冲区
        buffer.put(str.getBytes());

        System.out.println("----put----");
        System.out.println(buffer.position());
        System.out.println(buffer.limit());
        System.out.println(buffer.capacity());

        //切换到读取数据模式
        buffer.flip();

        System.out.println("----flip----");
        System.out.println(buffer.position());
        System.out.println(buffer.limit());
        System.out.println(buffer.capacity());

        //get读取缓冲区的数据
        byte[] dst = new byte[buffer.limit()];
        buffer.get(dst);
        System.out.println(new String(dst,0,dst.length));

        System.out.println("----get----");
        System.out.println(buffer.position());
        System.out.println(buffer.limit());
        System.out.println(buffer.capacity());

        //rewind():重复读
        buffer.rewind();
        System.out.println("----rewind----");
        System.out.println(buffer.position());
        System.out.println(buffer.limit());
        System.out.println(buffer.capacity());

        //clear:清空缓冲区，但是缓冲区的数据依然存在，处于“被遗忘”状态
        buffer.clear();
        System.out.println("----clear----");
        System.out.println(buffer.position());
        System.out.println(buffer.limit());
        System.out.println(buffer.capacity());

        System.out.println((char) buffer.get());
    }

    @Test
    public void test2(){
        String str = "abcde";

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.put(str.getBytes());
        buffer.flip();
        byte[] dst = new byte[buffer.limit()];
        buffer.get(dst, 0, 2);
        System.out.println(new String(dst, 0, 2));
        System.out.println(buffer.position());

        //标记
        buffer.mark();
        buffer.get(dst,2,2);
        System.out.println(new String(dst, 2, 2));
        System.out.println(buffer.position());

        //恢复到reset位置
        buffer.reset();
        System.out.println(buffer.position());

        //判断缓冲区是否还有可以操作的数据
        if (buffer.hasRemaining()){
            //输出缓冲区可以操作数据的长度
            System.out.println(buffer.remaining());
        }
    }
}
